{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-05T07:32:30.389145Z",
     "start_time": "2024-06-05T07:32:26.125448Z"
    },
    "is_executing": true
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch import optim\n",
    "from datasets import data_loader, text_ClS\n",
    "from config import Config\n",
    "from model import Model\n",
    "cfg = Config()\n",
    "data_path = \"sources/weibo_senti_100k.csv\" #训练集\n",
    "data_stop_path = \"sources/hit_stopword.txt\" #停用词\n",
    "dict_path = \"sources/dict\"  #词典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2024-06-05T07:32:36.764Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\admin\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 0.583 seconds.\n",
      "Prefix dict has been built successfully.\n"
     ]
    }
   ],
   "source": [
    "#获取数据集\n",
    "dataset = text_ClS(dict_path, data_path, data_stop_path) #全量的微博数据集\n",
    "train_dataloader = data_loader(dataset, cfg) #batch_size generator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2024-06-05T07:31:17.336Z"
    }
   },
   "outputs": [],
   "source": [
    "#实例化模型\n",
    "\n",
    "# from model import Model\n",
    "\n",
    "model_text_cls = Model(cfg)\n",
    "model_text_cls.to(cfg.device) #to()函数指定你的模型在什么设备运行\n",
    "loss_func = nn.CrossEntropyLoss() #损失函数\n",
    "optimizer = optim.Adam(model_text_cls.parameters(), lr=cfg.lr) #优化器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#模型的训练\n",
    "\n",
    "for epoch in range(cfg.num_epochs):\n",
    "    for i, batch in enumerate(train_dataloader):\n",
    "        label, data = batch\n",
    "        data = torch.tensor(data.long()).to(cfg.devices)\n",
    "        label = torch.tensor(label, dtype=torch.int64).to(cfg.devices)\n",
    "        pred = model_text_cls.forward(data) #模型的输出值\n",
    "        loss_val = loss_func(pred, label)\n",
    "        \n",
    "        optimizer.zero_grad() #梯度清零\n",
    "        loss_val.backward()\n",
    "        optimizer.step()\n",
    "        \n",
    "        if i % 100 == 0:\n",
    "            print(\"epoch is:{}, iter is:{}, loss_val is: {}\".format(epoch, i, loss_val)) #每100个iter输出一次损失值\n",
    "    \n",
    "    if epoch % 10 == 0:\n",
    "        torch.save(model_text_cls.state_dict(), \"models/{}.pth\".format(epoch))\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#模型推理\n",
    "model_text_cls.load_state_dict(torch.load(\"models/0.pth\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i, batch in enumerate(train_dataloader):\n",
    "    label, data = batch\n",
    "    data = torch.tensor(data.long()).to(cfg.devices)\n",
    "    label = torch.tensor(label, dtype=torch.int64).to(cfg.devices)\n",
    "    pred = model_text_cls.forward(data) #模型的输出值\n",
    "    pred = torch.argmax(pred, dim=1)\n",
    "    \n",
    "    out = torch.eq(pred, label)\n",
    "    accuracy = out.sum()*1.0 / pred.size()[0]\n",
    "    print(\"iter is:{}, accuracy is:{}\".format(i, accuracy))\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
